package ucanuup.cc.api.power.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import ucanuup.cc.api.power.dao.PowerUserDao;
import ucanuup.cc.api.power.entity.PowerUser;
import ucanuup.cc.api.power.inter.PowerUserService;
import ucanuup.cc.common.web.query.BaseQuery;
import ucanuup.cc.string.StringUtil;

/**
 * 管理员权限表管理类
 */
@Service
public class PowerUserServiceImpl implements PowerUserService {

	@Autowired
	private  PowerUserDao powerUserDao;

	@Override
	public PowerUser save(PowerUser entity) {
		return powerUserDao.save(entity);
	}

	@Override
	public Page<PowerUser> queryBaseUser(BaseQuery query) throws Exception {
		PageRequest pageable = PageRequest.of(query.getPageNo(), query.getPageSize());
		final PowerUser user = query.cast2Object(PowerUser.class);
		Specification<PowerUser> specification = new Specification<PowerUser>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<PowerUser> root,CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
				Predicate deleted = criteriaBuilder.equal(root.get("deleted").as(Integer.class),0);
				list.add(deleted);
				// 查询用户工号
				if(StringUtil.isNotEmpty(user.getUserAccount())) {
					Predicate userAccount = criteriaBuilder.like(root.get("userAccount").as(String.class), StringUtil.addSqlLike(user.getUserAccount()));
					list.add(userAccount);
				}
				// 查询用户名字
				if(StringUtil.isNotEmpty(user.getUserName())) {
					Predicate userName = criteriaBuilder.like(root.get("userName").as(String.class), StringUtil.addSqlLike(user.getUserName()));
					list.add(userName);
				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		};
		return powerUserDao.findAll(specification, pageable);
	}

	@Override
	public Iterable<PowerUser> saveAll(Iterable<PowerUser> entities) {
		return powerUserDao.saveAll(entities);
	}

	@Override
	public Page<PowerUser> queryUserByRole(BaseQuery query) throws Exception {
		return null;
	}
	
	
}
